<template>
	<div v-loading="loading" class="manage-coupon">
		<el-collapse-transition>
			<div v-show="!isShowDetail">
				<div class="top">
					<!-- <div class="app-main-top-box">
            <div class="title">卡管理</div>
          </div> -->
					<div class="create">
						<div class="card">
							<div class="title">
								<div>次卡</div>
								<el-button @click="jumpAdd('times')" type="primary">创建</el-button>
							</div>
							<div class="p">顾客一次购买/领取，多次核销，长期绑定顾客</div>
						</div>
						<div class="card">
							<div class="title">
								<div>礼品卡</div>
								<el-button @click="jumpAdd('gift')" type="primary">创建</el-button>
							</div>
							<div class="p">包含可消费余额，一次购买/领取支持分多次使用</div>
						</div>
					</div>

					<div class="tab">
						<el-tabs v-model="filterForm.status" @tab-click="changeTab">
							<!-- <el-tab-pane label="运营中" name="2" /> -->
							<el-tab-pane label="生效中" name="1" />
							<!-- <el-tab-pane label="已暂停" name="3" /> -->
							<!-- <el-tab-pane label="已终止" name="4" /> -->
							<el-tab-pane label="已结束" name="2" />
							<el-tab-pane label="草稿箱" name="3" />
							<!-- <el-tab-pane label="已过期" name="5" /> -->
						</el-tabs>
					</div>
				</div>

				<!-- 列表 -->
				<div class="content-main app-main-content-box">
					<!--筛选-->
					<el-form ref="filterForm" :inline="true" :model="filterForm" label-width="70px" size="small">
						<el-form-item label="名称：" prop="couponName"><el-input v-model="filterForm.couponName" placeholder="请输入" clearable /></el-form-item>
						<el-form-item label="批次：" prop="stockId"><el-input v-model="filterForm.stockId" placeholder="请输入" clearable /></el-form-item>
						<el-form-item label="类型：" prop="types">
							<el-select v-model="filterForm.types" filterable multiple collapse-tags placeholder="请选择" class="w-400" @change="val => idsChange(val, 'cardType')">
								<el-option label="所有类型" value />
								<el-option v-for="(v, k) in cardTypeOptions" :key="k" :label="v" :value="k" />
							</el-select>
						</el-form-item>
						<el-form-item v-if="filterForm.status === '1'" label="状态：" prop="openStatus">
							<el-select v-model="filterForm.openStatus" placeholder="请选择" class="w-400">
								<el-option label="所有" value />
								<el-option label="已启用" value="1"></el-option>
								<el-option label="已暂停" value="2"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item label-width="0">
							<el-button type="primary" round @click="submitFilterForm">查 询</el-button>
							<el-button round @click="resetFilterForm">重 置</el-button>
						</el-form-item>
					</el-form>
					<div>
						<el-row v-if="list.length > 0" :gutter="30" type="flex">
							<el-col v-for="(v, i) in list" :key="i" :xs="12" :sm="8" :md="8" :lg="8" :xl="6" class="coupon-card">
								<el-card shadow="hover" @click.native="showDetail(v)">
									<div class="coupon-content">
										<div class="coupon-base">
											<div class="left">
												<img v-if="v.icon" :src="fileBaseUrl + v.icon" alt />
												<el-image v-else :src="'static/icon/coupon/i-card-' + v.cardType + '.png'" fit="fill" />
											</div>
											<div class="right">
												<div class="name app-line-one">{{ v.cardName }}</div>
												<div class="type app-line-one">批次号：{{ v.id }} | {{ cardTypeOptions[v.cardType] }}</div>
											</div>
										</div>
										<div class="coupon-detail">
											<div v-if="['times'].includes(v.cardType)" class="cash">{{ v.times }}次</div>
											<div v-if="['gift'].includes(v.cardType)" class="cash">{{ v.denomination / 100 }}元</div>
										</div>
										<div class="coupon-more">
											<div class="date">有效期：{{ v.startTime + ' ~ ' + v.endTime }}</div>
											<div class="belong">归属人：{{ `${v.belongMerchantName}（${v.belongMerchant}）` }}</div>
										</div>
										<!--                    <div v-if="v.status===1" class="coupon-status">-->
										<!--                      <div v-if="!v.channelSync&&['cash_wx_busi','discount_wx_busi'].includes(v.couponType)&&v.syncMsg" class="app-text-color-danger">券渠道同步失败，请检查-->
										<!--                        <el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">-->
										<!--                          <div slot="content">-->
										<!--                            {{ v.syncMsg }}-->
										<!--                          </div>-->
										<!--                          <i class="el-icon-warning" />-->
										<!--                        </el-tooltip>-->
										<!--                      </div>-->
										<!--                      <div v-else-if="!v.channelSync&&['cash_wx_busi','discount_wx_busi'].includes(v.couponType)" class="app-text-color-warning">该批次需同步券渠道</div>-->
										<!--                      <div v-else class="app-text-color-primary">该批次激活即可使用</div>-->
										<!--                    </div>-->
									</div>
								</el-card>
							</el-col>
						</el-row>
						<!-- <div v-else class="empty-text">暂无数据</div> -->

						<!-- 表格 -->
						<el-table v-if="filterForm.status === '1'" :data="tableData" border key="2">
							<el-table-column prop="id" label="批次号"></el-table-column>
							<el-table-column prop="cardType" label="类型">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? '礼品卡' : '次卡' }}
								</template>
							</el-table-column>
							<el-table-column prop="cardName" label="名称"></el-table-column>
							<el-table-column prop="cardType" label="次数/金额">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? `${scope.row.denomination / 100}元` : `${scope.row.times}次` }}
								</template>
							</el-table-column>
							<el-table-column prop="sendCount" label="发放数"></el-table-column>
							<el-table-column prop="verifyCount" label="核销次数/金额">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? `${scope.row.verifyMoney / 100}元` : `${scope.row.verifyCount}次` }}
								</template>
							</el-table-column>
							<el-table-column prop="startTime" label="有效期">
								<template slot-scope="scope">
									{{ scope.row.startTime }} ~ {{ scope.row.endTime }}
								</template>
							</el-table-column>
							<el-table-column prop="openUp" label="状态">
								<template slot="header" slot-scope="scope">
									<span>状态</span>
									<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
										<div slot="content">
											<p>已启用表示可发放给用户使用；</p>
											<p style="margin-top: 8px;">已暂停表示卡不可发放给用户使用，暂停不影响已发放卡的使用</p>
										</div>
										<i class="el-icon-question" />
									</el-tooltip>
								</template>
								<template slot-scope="scope">
									{{ scope.row.openUp ? '已启用' : '已暂停' }}
								</template>
							</el-table-column>
							<el-table-column label="操作" width="150">
								<template slot-scope="scope">
									<el-button v-if="scope.row.openUp" @click="handleInto(scope.row, 'pause')" type="text" size="small">暂停</el-button>
									<el-button v-if="!scope.row.openUp" @click="handleInto(scope.row, 'enable')" type="text" size="small">启用</el-button>
									<el-button @click="handleInto(scope.row, 'stop')" type="text" size="small">终止</el-button>
									<el-button @click="handleInto(scope.row)" type="text" size="small">详情</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-table v-if="filterForm.status === '2'" :data="tableData" border key="4">
							<el-table-column prop="id" label="批次号"></el-table-column>
							<el-table-column prop="cardType" label="类型">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? '礼品卡' : '次卡' }}
								</template>
							</el-table-column>
							<el-table-column prop="cardName" label="名称"></el-table-column>
							<el-table-column prop="cardType" label="次数/金额">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? `${scope.row.denomination / 100}元` : `${scope.row.times}次` }}
								</template>
							</el-table-column>
							<el-table-column prop="sendCount" label="发放数"></el-table-column>
							<el-table-column prop="verifyCount" label="核销次数/金额">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? `${scope.row.verifyMoney / 100}元` : `${scope.row.verifyCount}次` }}
								</template>
							</el-table-column>
							<el-table-column prop="startTime" label="有效期">
								<template slot-scope="scope">
									{{ scope.row.startTime }} ~ {{ scope.row.endTime }}
								</template>
							</el-table-column>
							<el-table-column prop="endOperation" label="备注">
								<template slot-scope="scope">
									{{ scope.row.endOperation == 1 ? '自动结束' : '手动结束' }}
								</template>
							</el-table-column>
							<el-table-column label="操作" width="150">
								<template slot-scope="scope">
									<el-button @click="handleEnd(scope.row)" type="text" size="small">详情</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-table v-if="filterForm.status === '3'" :data="tableData" border key="1">
							<el-table-column prop="id" label="批次号"></el-table-column>
							<el-table-column prop="cardType" label="类型">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? '礼品卡' : '次卡' }}
								</template>
							</el-table-column>
							<el-table-column prop="cardName" label="名称"></el-table-column>
							<el-table-column prop="cardType" label="次数/金额">
								<template slot-scope="scope">
									{{ scope.row.cardType === 'gift' ? `${scope.row.denomination / 100}元` : `${scope.row.times}次` }}
								</template>
							</el-table-column>
							<el-table-column prop="startTime" label="有效期">
								<template slot-scope="scope">
									{{ scope.row.startTime }} ~ {{ scope.row.endTime }}
								</template>
							</el-table-column>
							<el-table-column label="操作" width="150">
								<template slot-scope="scope">
									<el-button @click="handleDraft(scope.row, 'enable')" type="text" size="small">启用</el-button>
									<el-button @click="handleDraft(scope.row, 'delet')" type="text" size="small">删除</el-button>
									<el-button @click="handleDraft(scope.row)" type="text" size="small">详情</el-button>
								</template>
							</el-table-column>
						</el-table>

						<pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange" />
					</div>
				</div>
			</div>
		</el-collapse-transition>

		<!-- 效果详情 -->
		<el-collapse-transition><CardInfo v-if="isShowDetail" ref="cardInfo" /></el-collapse-transition>
	</div>
</template>

<script>
import CardInfo from './components/CardInfo';
import { cardList, searchCard, statusCard, deleteDraft } from '../../api/card';
import { mapGetters } from 'vuex';
export default {
	components: {
		CardInfo
	},
	data() {
		return {
			// 配置
			cardTypeOptions: {
				times: '次卡',
				gift: '礼品卡'
			},
			// 状态
			loading: false,
			isShowDetail: false,
			// 数据
			lastCardTypesIds: [],
			cardTypesIds: ['', 'times', 'gift'],
			list: [], // 列表
			filterForm: {
				status: '1',
				couponName: null,
				stockId: null,
				types: [],
				openStatus: ''
			},
			// 分页配置
			paginationConfig: {
				direction: 'center', // 分页位置
				layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
				pageSizes: [10, 20], // 分页pages
				total: 0,
				page: 1, // 页数-默认1
				pageSize: 10 // 每页条数-默认10
			},
			tableData: []
		};
	},
	computed: {
		...mapGetters(['fileBaseUrl'])
	},
	activated() {
		this.isShowDetail = false;
		this.fetchData();
	},
	created() {},
	mounted() {
		// this.fetchData()
	},
	methods: {
		/**
		 *  获取数据
		 */
		// 列表
		fetchData() {
			this.loading = true;
			if (this.$route.params.saveType === 'on') {
				this.filterForm.status = '1';
				this.paginationConfig.total = 0;
				this.paginationConfig.page = 1;
			} else if (this.$route.params.saveType === 'draft') {
				this.filterForm.status = '3';
				this.paginationConfig.total = 0;
				this.paginationConfig.page = 1;
			}
			const params = this.filterForm;
			// cardList(params)
			// 	.then(res => {
			// 		this.list = res.data;
			// 	})
			// 	.catch(() => {})
			// 	.finally(() => {
			// 		this.loading = false;
			// 	});
			params.pageSize = this.paginationConfig.pageSize;
			params.pageNum = this.paginationConfig.page;
			params.name = this.filterForm.couponName;
			params.cardId = this.filterForm.stockId;
			params.type = this.filterForm.types;
			console.log('走 params',params)
			searchCard(params)
				.then(res => {
					this.tableData = res.data.list;
					this.paginationConfig.total = res.data.total;
					this.paginationConfig.page = res.data.pageNum;
				})
				.catch(err => {})
				.finally(() => {
					this.loading = false;
				});
		},

		/**
		 * 按钮组
		 */
		// 切换tab
		changeTab() {
			this.$route.params.saveType = ''
			this.fetchData();
		},

		// 查询
		submitFilterForm() {
			this.fetchData(1);
		},

		// 重置
		resetFilterForm() {
			this.$refs.filterForm.resetFields();
			this.fetchData(1);
		},

		// 获取详情
		showDetail(row) {
			this.isShowDetail = true;
			this.$nextTick(() => {
				this.$refs.cardInfo.show(row).then(res => {
					this.fetchData();
					this.isShowDetail = false;
				});
			});
		},

		// 分页sizes改变
		sizesChange() {
			this.fetchData();
		},
		// 分页page改变
		pageChange() {
			this.fetchData();
		},

		/**
		 * 状态组
		 */
		// 多选改变
		idsChange(val, type) {
			let lastIdsType = '';
			let idsType = '';
			let allIds = '';
			switch (type) {
				case 'cardType':
					lastIdsType = 'lastCardTypesIds';
					idsType = 'types';
					allIds = 'cardTypesIds';
					break;
			}
			const lastVal = this[lastIdsType];
			if (val.includes('')) {
				this.filterForm[idsType] = this[allIds];
			}
			if (lastVal.includes('') && !val.includes('')) {
				this.filterForm[idsType] = [];
			}
			if (lastVal.includes('') && val.includes('')) {
				val.splice(val.findIndex(v => v === ''), 1);
				this.filterForm[idsType] = val;
			}
			if (!lastVal.includes('') && !val.includes('')) {
				if (val.length === this[allIds].length - 1) {
					this.filterForm[idsType] = [''].concat(val);
				}
			}
			this[lastIdsType] = this.filterForm[idsType];
		},

		jumpAdd(cardType) {
			this.$router.push({
				name: 'CardsAndOfferEditCard',
				query: { mode: 'add', cardType }
			});
		},
		handleInto(row, type) {
			if (type === 'pause') {
				let confirmText = ['是否暂停当前卡？', '注：暂停后不影响已发放的卡，但是不能继续给用户发放，启用后可继续发放'];
				const newDatas = [];
				const h = this.$createElement; //先用$createElement创建h函数。
				for (const i in confirmText) {
					newDatas.push(h('p', confirmText[i]));
				}
				this.$confirm('提示', {
					title: '提示',
					message: h('div', null, newDatas),
					confirmButtonText: '是',
					cancelButtonText: '否',
					type: 'warning'
				})
					.then(() => {
						this.statusCardFun(row, type);
					})
					.catch(() => {});
			} else if (type === 'stop') {
				let confirmText = ['是否终止当前卡？', '注：终止后将不可再次启用，并不影响已发放券的使用'];
				const newDatas = [];
				const h = this.$createElement; //先用$createElement创建h函数。
				for (const i in confirmText) {
					newDatas.push(h('p', confirmText[i]));
				}
				this.$confirm('提示', {
					title: '提示',
					message: h('div', null, newDatas),
					confirmButtonText: '是',
					cancelButtonText: '否',
					type: 'warning'
				})
					.then(() => {
						this.statusCardFun(row, type);
					})
					.catch(() => {});
			} else if (type === 'enable') {
				let confirmText = ['是否启用当前卡？', '注：启用后可在商户后台发放给用户'];
				const newDatas = [];
				const h = this.$createElement; //先用$createElement创建h函数。
				for (const i in confirmText) {
					newDatas.push(h('p', confirmText[i]));
				}
				this.$confirm('提示', {
					title: '提示',
					message: h('div', null, newDatas),
					confirmButtonText: '是',
					cancelButtonText: '否',
					type: 'warning'
				})
					.then(() => {
						this.statusCardFun(row, type);
					})
					.catch(() => {});
			} else {
				this.showDetail(row);
			}
		},
		handleEnd(row, type) {
			this.showDetail(row);
		},
		handleDraft(row, type) {
			if (type === 'enable') {
				let confirmText = ['是否启用当前卡？', '注：启用后可在商户后台发放给用户'];
				const newDatas = [];
				const h = this.$createElement; //先用$createElement创建h函数。
				for (const i in confirmText) {
					newDatas.push(h('p', confirmText[i]));
				}
				this.$confirm('提示', {
					title: '提示',
					message: h('div', null, newDatas),
					confirmButtonText: '是',
					cancelButtonText: '否',
					type: 'warning'
				})
					.then(() => {
						this.statusCardFun(row, type);
					})
					.catch(() => {});
			} else if (type === 'delet') {
				let confirmText = ['是否删除当前卡？', '注：注：删除后不可找回，请谨慎操作。'];
				const newDatas = [];
				const h = this.$createElement; //先用$createElement创建h函数。
				for (const i in confirmText) {
					newDatas.push(h('p', confirmText[i]));
				}
				this.$confirm('提示', {
					title: '提示',
					message: h('div', null, newDatas),
					confirmButtonText: '是',
					cancelButtonText: '否',
					type: 'warning'
				})
					.then(() => {
						this.deleteDraftFun(row);
					})
					.catch(() => {});
			} else {
				this.showDetail(row);
			}
		},

		// 卡状态
		statusCardFun(row, type) {
			let { id } = row;
			let filStatus = this.filterForm.status;
			let _status = '';
			if (filStatus == 1 && type === 'pause') {
				_status = 2;
			} else if (filStatus == 1 && type === 'enable') {
				_status = 4;
			} else if (filStatus == 3 && type === 'enable') {
				_status = 1;
			} else {
				_status = 3;
			}
			let params = {
				// 操作，1：草稿箱--启用，2：生效中--暂停，3：生效中--终止，4：生效中--启用
				status: _status,
				// 批次号
				stockId: id
			};
			statusCard(params).then(res => {
				this.fetchData();
			});
		},
		//删除卡
		deleteDraftFun(row) {
			let { id } = row;
			let params = {
				// 批次号
				id
			};
			deleteDraft(params).then(res => {
				this.fetchData();
			});
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* tab */
::v-deep {
	.el-tabs__header {
		margin-bottom: 0;
		background-color: #fff;
		border-radius: 0 0 5px 5px;
	}
	.el-tabs__nav-wrap::after {
		background-color: #fff;
	}
	.el-tabs__active-bar {
		height: 4px;
	}
	.el-row {
		flex-wrap: wrap;
	}
	.el-card,
	.el-card__body {
		height: 100%;
	}
}

/* 头部 */
.top {
	padding: 24px 30px 0;
	border-radius: 5px 5px;
	background-color: #fff;
	margin-bottom: 10px;
	.title {
		font-size: 20px;
	}

	/* create */
	.create {
		width: 100%;
		min-height: 150px;
		overflow: hidden;

		.card {
			width: 250px;
			overflow: hidden;
			background-color: #f2f2f2;
			padding: 8px;
			box-sizing: border-box;
			border-radius: 8px;
			float: left;
			margin-right: 20px;

			.title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-weight: bold;
			}

			.p {
				margin-top: 20px;
			}
		}
	}
}

.empty-text {
	line-height: 60px;
	text-align: center;
	color: #909399;
	font-size: 14px;
}

/* 卡片 */
.coupon-card {
	margin-bottom: 20px;
	//height: 270px;
	cursor: pointer;
	.coupon-content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100%;
	}
	.coupon-base {
		display: flex;
		.left {
			overflow: hidden;
			flex: 0 0 auto;
			width: 80px;
			height: 80px;
			margin-right: 15px;
			border-radius: 50%;
			border: 1px solid #e7e7e7;
		}
		.right {
			flex: 1 1 auto;
			display: flex;
			flex-direction: column;
			justify-content: center;
			.name {
				font-size: 20px;
				// margin-top: 25px;
				font-weight: bold;
			}
			.type {
				margin-top: 5px;
				font-size: 14px;
				color: #909399;
			}
		}
	}
	.coupon-detail {
		text-align: center;
		border-bottom: 1px solid #e7e7e7;
		height: 90px;
		.cash,
		.discount,
		.exchange {
			font-size: 24px;
			margin-top: 10px;
			font-weight: bold;
		}
		.describe {
			margin-top: 10px;
			font-size: 14px;
			color: #909399;
		}
	}
	.coupon-more {
		margin-top: 10px;
		font-size: 14px;
		color: #909399;
		.date {
		}
		.belong {
		}
	}
	.coupon-status {
		margin-top: 10px;
		padding-top: 10px;
		border-top: 1px solid #e7e7e7;
		font-size: 14px;
	}
}
</style>
